package model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArrayList;

import model.enemies.CreateEnemiesThread;
import model.enemies.IEnemy;
import model.surface.Grid;
import model.surface.Map;
import model.towers.ITower;

/**
 * The Class holds a number of collections where is saved the current state of
 * the game.
 * 
 * @author EvilTeam
 * 
 */
public class DataHolder {
	private static ArrayList<CreateEnemiesThread> threads = new ArrayList<CreateEnemiesThread>();
	private static CopyOnWriteArrayList<ITower> towers = new CopyOnWriteArrayList<ITower>();
	private static CopyOnWriteArrayList<IEnemy> enemies = new CopyOnWriteArrayList<IEnemy>();

	public static ArrayList<CreateEnemiesThread> getThreads() {
		return threads;
	}

	public static void addThread(CreateEnemiesThread thread) {
		threads.add(thread);
	}

	public static CopyOnWriteArrayList<ITower> getTowers() {
		return towers;
	}

	public static void addTower(ITower tower) {
		towers.add(tower);
		sortTheTowers();
	}

	/**
	 * Sorting the towers in the right order on the game board
	 */
	private static void sortTheTowers() {
		Object[] array = towers.toArray();
		Arrays.sort(array);
		towers.clear();
		for (Object obj : array) {
			if (obj instanceof ITower) {
				ITower orderedTower = (ITower) obj;
				towers.add(orderedTower);
			}
		}
	}

	public static CopyOnWriteArrayList<IEnemy> getEnemies() {
		return enemies;
	}

	public static void addEnemy(IEnemy enemy) {
		enemies.add(enemy);
	}

	/**
	 * Clears all of the collections.
	 */
	@SuppressWarnings("unused")
	public static void clearData() {
		for (IEnemy enemy : enemies) {
			enemy = null;
		}
		for (ITower tower : towers) {
			tower.getStartShootingThread().stopShooting();
			tower = null;
		}
		for (CreateEnemiesThread thread : threads) {
			thread = null;
		}
		enemies.clear();
		threads.clear();
		towers.clear();
		Grid.cleanGrid();
		Map.cleanMap();
	}
}
